package com.liangtian.mdm.dm.jsp.common;

import com.liangtian.mdm.dm.common.constant.UrlConst;
import com.liangtian.mdm.dm.common.enums.Type;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.model.model.Model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DetailJsCreate {

    /**
     * Title: 替换修改js文件
     */
    public static String ReplaceAll(String operType, String readFilePath, String script, List<AttrConfig> list, Model model, Map<String, Object> map) {
        String tableName = model.getTableName();
        script = script.replace("{ngApp}", tableName + operType + "App")
                .replace("{ngControl}", tableName + operType + "Control")
                .replace("{tablename}", tableName);
        if ("detail".equals(operType) || "treeTabDetail".equals(operType)) {
            script = script.replace("{detailReBackUrl}", detailReBackUrl(model, operType));
        }
        script = script.replace("{formId}", tableName).replace("{formName}", tableName)
                .replace("{selectControl}", UrlConst.ONEURL)
                .replace("{detailControl}", UrlConst.DETAILURL)
                .replace("{UpdateControl}", UrlConst.UPDATEURL)
                .replace("{MainColumn}", JspUtil.spellColumn(model, Type.MAIN))
                .replace("{DetailColumn}", JspUtil.spellColumn(model, Type.DETAIL))
                .replace("{DataList}", (String) map.get("res"))
                .replace("{modelId}", tableName.split("_")[1]).replace("@R#", "\r\n");
        return script;
    }

    /**
     * * <p>Title: 动态替换生成的日期js语句</p>
     *
     * @author : xiaoliu
     * @date :2016年8月8日下午2:17:30
     */
    public static Map<String, Object> ReplaceDataLists(List<AttrConfig> attrList) {
        Map<String, Object> resMap = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        List<AttrConfig> fileLst = new ArrayList<AttrConfig>();
        if (attrList != null) {
            for (int i = 0; i < attrList.size(); i++) {
                String column = attrList.get(i).getAttrColumn().toLowerCase();
                sb.append("		    $scope." + column + "=data." + column + "; \r\n");
                if ("BLOB".equals(attrList.get(i).getAttrType())) {
                    fileLst.add(attrList.get(i));
                    sb.append("   if(undefined == $scope." + column + "){ \r\n")
                            .append("     $(document.getElementById('" + column + "Button')).hide(); \r\n")
                            .append("     $scope." + column + "='未上传文件!'; \r\n")
                            .append("   }else if(data.fileSize==1){ \r\n")
                            .append("      $('#" + column + "Button').show(); \r\n")
                            .append("   }else{ \r\n")
                            .append("      $('#" + column + "lookButton').show(); \r\n")
                            .append("   }  \r\n");
                }
            }

            resMap.put("res", sb.toString());
            resMap.put("fileLst", fileLst);
        }

        return resMap;
    }

    /**
     * * <p>Title: 生成替换js模板</p>
     *
     * @author : xiaoliu
     * @date :2016年8月8日下午2:21:25
     */
    @SuppressWarnings("unchecked")
    public static void creatDetailJs(String readFilePath, Model model, List<AttrConfig> configLst, String operType, Map<String, Object> result_map) {
        //operType操作（detail,treeTabDetail）
        String script = "";
        try {
            script = JspUtil.getTmpJspContent(readFilePath); // 获取js页面内容
            Map<String, Object> map = ReplaceDataLists(configLst);
            List<AttrConfig> fileLst = (List<AttrConfig>) map.get("fileLst");
            if (!fileLst.isEmpty()) {
                String fileCol = null;
                StringBuffer sb = new StringBuffer();
                StringBuffer hideSb = new StringBuffer();
                for (AttrConfig ac : fileLst) {
                    fileCol = ac.getAttrColumn().toLowerCase();
                    sb.append(" $('#" + fileCol + "lookButton').click(function (){ \r\n");
                    if (model.getClassType().equals("0")) {
                        sb.append("     $('#c_lookFilesModal').modal({remote: '" + model.getTableName() + "_checkFiles.jsp?surveyType='+'" + model.getId() + "'+'&dataId='+$scope.id+'&operType='+style+'&fileColumn='+'" + fileCol + "'}); \r\n");
                    } else {
                        sb.append("     $('#c_lookFilesModal').modal({remote: '" + model.getTableName() + "_treeTabCheckFiles.jsp?surveyType='+'" + model.getId() + "'+'&dataId='+$scope.id+'&operType='+style+'&fileColumn='+'" + fileCol + "'}); \r\n");
                    }
                    sb.append(" }) \r\n");
                    sb.append("$scope." + fileCol + "downLoad = function() {  \r\n ")
                            .append("$('#dataId').val($scope.id); \r\n")
                            .append("$('#surveyType').val('" + model.getId() + "'); \r\n")
                            .append("$('#fileColumn').val('" + fileCol + "'); \r\n")
                            .append("$('#Fileform')[0].action =basePath+'/file/download'; \r\n ")
                            .append("$('#Fileform')[0].submit();  \r\n ")
                            .append("} \r\n");

                    hideSb.append(" $(document.getElementById('" + fileCol + "Button')).hide(); \r\n")
                            .append(" $(document.getElementById('" + fileCol + "lookButton')).hide(); \r\n");
                }
                sb.append("$('#c_lookFilesModal').on('hidden.bs.modal', function() {  \r\n")
                        .append("$(this).removeData('bs.modal'); \r\n")
                        .append(" }); \r\n");

                script = script.replace("{downLoadFileFun}", sb.toString());
                script = script.replace("{filesButHide}", hideSb.toString());
            } else {
                script = script.replace("{downLoadFileFun}", "");
                script = script.replace("{filesButHide}", "");
            }

            script = DetailJsCreate.ReplaceAll(operType, readFilePath, script, configLst, model, map);
            JspUtil.writeInJsp(script, readFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String, Object> createDetailParams(Model model, String operType, List<AttrConfig> configLst) {
        Map<String, Object> param = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        List<AttrConfig> acLst = new ArrayList<AttrConfig>();
        for (int i = 0; i < configLst.size(); i++) {
            String column = configLst.get(i).getAttrColumn().toLowerCase();
            sb.append("'" + column + "':").append("$scope.").append(column).append(", \r\n");
            if (configLst.get(i).getAttrType() != null && "BLOB".equals(configLst.get(i).getAttrType()))
                acLst.add(configLst.get(i));
        }
        param.put("sb", sb.toString());
        param.put("fileLst", acLst);
        return param;
    }

    //传递一个参数Model
    public static String detailReBackUrl(Model model, String operType) {
        StringBuilder sb = new StringBuilder();
        String tableName = model.getTableName();//获取模型表名
        if ("0".equals(model.getModelType())) {//判断是不是主数据--主数据
            if ("0".equals(model.getClassType())) {//判断是不是列表---列表
                if (model.getIsSubtable() != 1) {//判断是不是从表---不是从表
                    sb.append("            var url = '';  $RN$")
                            .append("                  if(style=='list'){  $RN$")
                            .append("                       url=basePath+" + "'/am/" + tableName + "/" + tableName + "_list.jsp'" + ";  $RN$")
                            .append("                   }  $RN$")
                            .append("                  else if(style=='apply'){  $RN$")
                            .append("                       url=basePath+" + "'/am/" + tableName + "/" + tableName + "_apply.jsp'" + ";  $RN$")
                            .append("                   }  $RN$")
                            .append("                  else if(style=='update'){  $RN$")
                            .append("                      url=basePath+" + "'/am/" + tableName + "/" + tableName + "_update.jsp'" + ";  $RN$")
                            .append("                 }  $RN$")
                            .append("                 else{  $RN$")
                            .append("                     url=basePath+" + "'/am/" + tableName + "/" + tableName + "_approve.jsp'" + ";  $RN$")
                            .append("                }  $RN$")
                            .append("            if(null != $('#mainId').val()){  $RN$")
                            .append("                    url = url + '?mainId='" + "+$('#mainId').val();  $RN$")
                            .append("             }  $RN$")
                            .append("                location.href = url;  $RN$");
                } else {//是从表--------------------------------------------------------------------------------
                    sb.append("          if(style=='list'){  $RN$")
                            .append("               var url=basePath+" + "'/am/" + tableName + "/" + tableName + "_list.jsp'" + ";  $RN$")
                            .append("                 if(null != $('#mainId').val()){  $RN$")
                            .append("                    url = url + '?mainId='" + "+$('#mainId').val();  $RN$")
                            .append("                  }  $RN$")
                            .append("                location.href = url;  $RN$")
                            .append("           }  $RN$")
                            .append("           else if(style=='apply'){  $RN$")
                            .append("               var url=basePath+" + "'/am/" + tableName + "/" + tableName + "_apply.jsp'" + ";  $RN$")
                            .append("                   if(null != $('#mainId').val()){  $RN$")
                            .append("                        url = url + '?mainId='" + "+$('#mainId').val();  $RN$")
                            .append("                   }  $RN$")
                            .append("                  location.href = url;  $RN$")
                            .append("               }  $RN$")
                            .append("           else if(style=='update'){  $RN$")
                            .append("                 var url=basePath+" + "'/am/" + tableName + "/" + tableName + "_update.jsp'" + ";  $RN$")
                            .append("                  if($('#originId').val()){  $RN$")
                            .append("                    url = url + '?mainId='" + "+$('#originId').val();  $RN$")
                            .append("                  }  $RN$")
                            .append("                  location.href = url;  $RN$")
                            .append("               }  $RN$")
                            .append("            else{  $RN$")
                            .append("                  var url=basePath+" + "'/am/" + tableName + "/" + tableName + "_approve.jsp'" + ";  $RN$")
                            .append("                   if($('#originId').val()){  $RN$")
                            .append("                     url = url + '?mainId='" + "+$('#originId').val();  $RN$")
                            .append("             }  $RN$")
                            .append("          location.href = url;  $RN$");
                }
            } else {
                if (model.getIsSubtable() != 1) {//判断是不是从表---不是从表
                    sb.append("         var url = '';  $RN$")
                            .append("           if(style=='list'){  $RN$")
                            .append("               url=basePath+" + "'/am/" + tableName + "/" + tableName + "_treeTabList.jsp'" + ";  $RN$")
                            .append("           }  $RN$")
                            .append("           else if(style=='apply'){  $RN$")
                            .append("               url=basePath+" + "'/am/" + tableName + "/" + tableName + "_treeTabApply.jsp'" + ";  $RN$")
                            .append("           }  $RN$")
                            .append("           else if(style=='update'){  $RN$")
                            .append("               url=basePath+" + "'/am/" + tableName + "/" + tableName + "_treeTabUpdate.jsp'" + ";  $RN$")
                            .append("           }  $RN$")
                            .append("           else{  $RN$")
                            .append("               url=basePath+" + "'/am/" + tableName + "/" + tableName + "_treeTabApprove.jsp'" + ";  $RN$")
                            .append("           }  $RN$")
                            .append("          if(null != $('#" + JspUtil.spellColumn(model, Type.DETAIL) + "').val()){$RN$")
                            .append("                 url = url + '?" + JspUtil.spellColumn(model, Type.MAIN) + "='" + "+$('#" + JspUtil.spellColumn(model, Type.DETAIL) + "').val();  $RN$")
                            .append("               if(null != $('#mainId').val()){  $RN$")
                            .append("                     url = url + '&mainId='" + "+$('#mainId').val();  $RN$")
                            .append("                }  $RN$")
                            .append("           }  $RN$")
                            .append("         location.href = url;  $RN$");
                }
            }
        }
        return sb.toString().replace("$RN$", "\r\n");
    }

    public static void createCheckFilesJs(String readFilePath, Model model) {
        String script = "";
        try {
            script = JspUtil.getTmpJspContent(readFilePath); // 获取js页面内容
            String tableName = model.getTableName();
            script = script.replace("{tableName}", tableName)
                    .replace("@R#", "\r\n");
            JspUtil.writeInJsp(script, readFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
